<template>
  <div id="preAcceptTypePie">
    <DecorativeTitle text="电话呼入类型"/>
    <div class="chart-container">
      <!-- 右上角总数显示 -->
      <div class="total-count">
        <span style="color: #3DE7C9; font-size: 14px;">总数:</span> {{ total }}
      </div>
      <Chart :cdata="cdata"/>
    </div>
  </div>
</template>

<script>
import DecorativeTitle from "_c/DecorativeTitle.vue";
import Chart from  "./chart.vue"
import {fetchDictListByName} from "@/utils/dictUtil";
import {getLast24HoursRange} from "@/utils/dateUtil";
import {getUnitCalItemsWithNoAuthorization} from "@/api/UnitCalculate";
import config from "@/config";

export default {
  name: "PreAcceptTypePie",
  components: {
    Chart,
    DecorativeTitle
  },
  props: {

  },
  data() {
    return {
      options: {},
      cdata: {
        xData: [],
        seriesData: []
      },
      total: 0,
      dictList: [],
      standardData: {
        beginDateTime: "",
        endDateTime: "",
        columnsData: [
          {
            columnHeadType: 1,
            commGroupInfo: {
              isCommonGroup: true,
              category: "EPAIPRE_ACCEPT_TYPE",
              categoryGroup: "EPAIPRE_ACCEPT_TYPE_1"
            },
            dataIndex: "CATE"
          },
          {
            columnHeadType:1,
            calculateIden: { title : "受理数" },
            calculateInfo: {
              offset: 0,
              dataCategory: 0,
              valueCategory: 0,
              count: true,
              differenceCount: false,
              proportion: false
            },
            dataIndex: "SLS"
          }
        ],
        verticalGroups: [
          {
            category: "EPAIPRE_ACCEPT_TYPE",
            categoryGroup: "EPAIPRE_ACCEPT_TYPE_1",
            level: 1,
            title: "预受理类型"
          }
        ],
        screens: [
          {
            ref: "EPAIAREA_CODE",
            checkIden: "EPAIAREA_CODE_1",
            rlevantData: {
              iden: "EPAIAREA_CODE_1",
              filterType: 2,
              value: [
                {
                  value: config.xzbm,
                  xzbm: config.xzbm
                }
              ]
            }
          }
        ]
      }
    }
  },
  async created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        if (!this.dictList || !this.dictList.length) {
          this.dictList = await fetchDictListByName("预受理类型");
        }
        const { beginDateTime, endDateTime } = getLast24HoursRange();
        this.standardData.beginDateTime = beginDateTime;
        this.standardData.endDateTime = endDateTime;
        const res = await getUnitCalItemsWithNoAuthorization(this.standardData);
        if (res.code === 200 && res.isSuccess) {
          const entityList = JSON.parse(res.entity);
          this.processData(entityList);
        } else {
          console.error('接口返回失败', res);
          this.resetData();
        }
      } catch (e) {
        console.error('数据处理异常', e);
        this.resetData();
      }
    },

    // 重置数据
    resetData() {
      this.total = 0;
      this.cdata = {
        xData: [],
        seriesData: []
      };
    },

    // 处理接口返回数据
    processData(entityList) {
      this.resetData();
      if (this.dictList && this.dictList.length) {
        if (entityList && entityList.length) {
          entityList.forEach(item => {
            // 过滤掉合计项和空CATE
            if (item.CATE && item.CATE !== '合计') {
              const count = Number(item.SLS) || 0;
              this.cdata.xData.push(item.CATE);
              this.cdata.seriesData.push({
                name: item.CATE,
                value: count
              });
              this.total += count;
            }
          });
        } else {
          for (let i = 0; i < this.dictList.length; i++) {
            const title = this.dictList[i].title;
            this.cdata.xData.push(title);
            this.cdata.seriesData.push({
              name: title,
              value: 0
            });
            if (i >= 5) {
              break;
            }
          }
          this.total = 0;
        }
      } else {
        if (entityList && entityList.length) {
          // 分离合计项和普通项
          const totalItem = entityList.find(item => item.CATE === '合计');
          const normalItems = entityList.filter(item => item.CATE !== '合计' && item.CATE); // 排除空类型

          // 设置总数（优先使用合计项，没有则计算总和）
          this.total = totalItem
              ? Number(totalItem.SLS)
              : normalItems.reduce((sum, item) => sum + Number(item.SLS), 0);

          // 组装图表数据
          this.cdata.xData = normalItems.map(item => item.CATE);
          this.cdata.seriesData = normalItems.map(item => ({
            name: item.CATE,
            value: Number(item.SLS)
          }));
        }
      }
    },

  }
};
</script>

<style lang="scss" scoped>
$box-height: 290px;
#preAcceptTypePie {
  padding: 15px;
  width: 100%;
  height: $box-height;
  position: relative;
}

.chart-container {
  position: relative;
  width: 100%;
  padding-top: 15px;
  height: 180px;
}

.total-count {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0px 10px;
  color: #FFF;
  font-size: 18px;
  font-weight: bold;
  z-index: 10;
}
</style>
